/**
 * WebGL代码执行器
 */

export interface CodeRunnerOptions {
  canvas: HTMLCanvasElement
  vertexShaderSource: string
  fragmentShaderSource: string
  jsCode: string
  onLog?: (type: 'log' | 'error' | 'warn' | 'info', message: string) => void
}

/**
 * 创建沙盒环境并执行用户代码
 */
export const runWebGLCode = (options: CodeRunnerOptions): void => {
  const { canvas, vertexShaderSource, fragmentShaderSource, jsCode, onLog } = options

  // 清空画布
  const gl = canvas.getContext('webgl')
  if (gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
  }

  // 创建沙盒环境
  const sandbox = {
    canvas,
    vertexShaderSource,
    fragmentShaderSource,
    console: {
      log: (...args: any[]) => onLog?.('log', args.join(' ')),
      error: (...args: any[]) => onLog?.('error', args.join(' ')),
      warn: (...args: any[]) => onLog?.('warn', args.join(' ')),
      info: (...args: any[]) => onLog?.('info', args.join(' ')),
    },
    requestAnimationFrame: window.requestAnimationFrame.bind(window),
    Date: Date,
    Math: Math,
    Float32Array: Float32Array,
  }

  // 执行用户代码
  const func = new Function(...Object.keys(sandbox), jsCode)
  func(...Object.values(sandbox))
}

/**
 * 清空画布
 */
export const clearCanvas = (canvas: HTMLCanvasElement): boolean => {
  const gl = canvas.getContext('webgl')
  if (gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    return true
  }
  return false
}

